<template>
  <view style="position: relative;"  class="add-address-view need_scroll_top_view">
    <form>
      <view class="btn_div" :style="{'height': (systemWindowHeight) + 'px'}">
        <view class="unction_btn ">
          <text class="btn_font">收货人</text>
          <input class="uni-input" type="text" placeholder="填写收货人姓名" placeholder-class="input-placeholder" v-model="addressInfo.contact" @blur="backFixationTop()"/>
        </view>
        <view class="unction_btn ">
          <text class="btn_font">联系电话</text>
          <input class="uni-input" type="number" placeholder="填写收货人手机号" placeholder-class="input-placeholder" v-model="addressInfo.contactMobile" @blur="backFixationTop()"/>
        </view>
        <view class="unction_btn ">
          <text class="btn_font">所在区域</text>
          <view class="uni-input2">
            <picker :value="multiDistrictIndex" range-key="name" :range="multiDistrictArray" @cancel="bindDistrictPickerCancel" @change="bindDistrictPickerChange" @columnchange="bindDistrictColumnPickerChange" class="form-item-pick" mode="multiSelector" name="picker">
              <view class="pick-value-select" v-if="multiDistrictArray && multiDistrictArray.length > 0 && selectDistrict">
                <text v-if="multiDistrictArray[0] && multiDistrictArray[0][multiDistrictIndex[0]]">{{multiDistrictArray[0][multiDistrictIndex[0]].name}}</text>
                <text v-if="multiDistrictArray[1] && multiDistrictArray[1][multiDistrictIndex[1]]">{{multiDistrictArray[1][multiDistrictIndex[1]].name}}</text>
                <text v-if="multiDistrictArray[2] && multiDistrictArray[2][multiDistrictIndex[2]]">{{multiDistrictArray[2][multiDistrictIndex[2]].name}}</text>
              </view>
              <view class="pick-value" v-else>请选择所在区域</view>
            </picker>
          </view>
          <view class="arrow"></view>
        </view>
        <view class="">
          <textarea @blur="backFixationTop()" auto-height placeholder="请填写详细地址" placeholder-class="textarea-placeholder" class="uni-input1" v-model="addressInfo.street"/>
          <!-- <textarea class="uni-input1" auto-height placeholder="请填写详细地址" placeholder-class="textarea-placeholder" v-model="addressInfo.street"  @blur="backFixationTop()"/> -->
        </view>
      </view>
      <view class="uni-padding-wrap uni-common-mt">
        <button  type="parimay" @click="validForm">{{id ? '更新' : '保存'}}</button>
      </view>
    </form>
    
  </view>
</template>
<script>
import {AddressSave,AddressChioce,AddressFind,AddressUpdate} from '@/service/user/user.service.js'
import { multiDistrict } from '../../unit/common.js'
import graceChecker  from '@/unit/graceChecker.js'
import { scrollToTargetPosition } from '@/mixin/index.mixin.js'
export default {
  mixins: [scrollToTargetPosition],
  data() {
    return {
      selectDistrict: false,
      id: null, // 地址Id, 编辑的时候用到
      addressInfo: {
        contact : '', // 姓名
        contactMobile : '', // 手机号
        districtId: [], //  
        street:'', // 详细地址
      },
      // 省市区相关
      multiDistrictIndex: [], // 省市区选择的index
      multiDistrictArray: [], // 省市区数据 Array[Object]
      multiDistrictIds: [], // 省市区ID
      originMultiDistrictIndex: [], // 原始数据 用于取消选择省市区，还原原始数据
      originMultiDistrictArray: [], // 原始数据 用于取消选择省市区，还原原始数据
      originMultiDistrictIds: [], // 原始数据 用于取消选择省市区，还原原始数据
      sourceType: null,
      sourceIsCar: null
    }
  },
  mounted () {
    //
  },
  onLoad (option) {
    this.sourceType = option.type;
    this.sourceIsCar = option.isCartBy;
    if (option.id) {
      this.id = option.id
      this.getAddressInfo();
    } else {
      this.initDistrictData();
    }
  },
  onShow () {
    
  },
  methods: {
    getAddressInfo () { // 获取编辑地址详情
      AddressFind({
        id: this.id
      }, (res) => {
        if(res.status == 0){
          this.addressInfo.contact = res.data.contact;
          this.addressInfo.contactMobile = res.data.mobile;
          this.addressInfo.street = res.data.street;
          this.selectDistrict = true;
          this.initDistrictData(res.data.districtIds);
        } 
      })
    },
    async initDistrictData (district) { // 初始化省市区数据
      let {multiDistrictArray, multiDistrictIndex, multiDistrictIds} = await multiDistrict.initMultDistrictArray({
        district: district
      });
      this.multiDistrictArray = multiDistrictArray;
      this.multiDistrictIndex = multiDistrictIndex;
      this.multiDistrictIds = multiDistrictIds;
      this.originMultiDistrictArray = JSON.parse(JSON.stringify(multiDistrictArray));
      this.originMultiDistrictIndex = JSON.parse(JSON.stringify(multiDistrictIndex));
      this.originMultiDistrictIds = JSON.parse(JSON.stringify(multiDistrictIds));
      this.addressInfo.districtId = this.multiDistrictIds[this.multiDistrictIds.length - 1];
    },
    bindDistrictPickerCancel (e) { // 取消省市区的选择
      this.multiDistrictArray = JSON.parse(JSON.stringify(this.originMultiDistrictArray));
      this.multiDistrictIndex = JSON.parse(JSON.stringify(this.originMultiDistrictIndex));
      this.multiDistrictIds = JSON.parse(JSON.stringify(this.originMultiDistrictIds));
      
    },
    bindDistrictPickerChange (e) { // 确认省市区的选择
      this.selectDistrict = true;
      this.originMultiDistrictArray = JSON.parse(JSON.stringify(this.multiDistrictArray));      
      this.originMultiDistrictIndex = JSON.parse(JSON.stringify(this.multiDistrictIndex));
      this.originMultiDistrictIds = JSON.parse(JSON.stringify(this.multiDistrictIds));
      this.addressInfo.districtId = this.multiDistrictIds[this.multiDistrictIds.length - 1];
    },
    async bindDistrictColumnPickerChange (e) { // 省市区的列发生变化
      if (e.detail.column < this.multiDistrictArray.length - 1) {
        let {multiDistrictArray, multiDistrictIndex, multiDistrictIds} = await multiDistrict.bindDistrictColumnPickerChange({
          column: e.detail.column,
          index: e.detail.value,
          multiDistrictIndex: JSON.parse(JSON.stringify(this.multiDistrictIndex)),
          multiDistrictArray: JSON.parse(JSON.stringify(this.multiDistrictArray))
        });
        this.multiDistrictArray = multiDistrictArray;
        this.multiDistrictIndex = multiDistrictIndex;
        this.multiDistrictIds = multiDistrictIds;
      } else {
        this.multiDistrictIndex.splice(e.detail.column, 1, e.detail.value);
        this.multiDistrictIds.splice(e.detail.column, 1, this.multiDistrictArray[e.detail.column][e.detail.value].id);
      }
    },
    validForm () {
      //定义表单规则
      let rule = [
        {name:"contact", checkType : "notnull", checkRule:"",  errorMsg: "请填写姓名"},
        {name:"contactMobile", checkType : "notnull", checkRule:"",  errorMsg:"请输入手机号"},
        {name:"contactMobile", checkType : "phoneno", checkRule:"",  errorMsg:"请输入正确的手机号"},
        {name:"districtId", checkType : "notnull", checkRule:"",  errorMsg:"请选择所在区域"},
        {name:"street", checkType : "notnull", checkRule:"",  errorMsg:"请输入详细地址"}
      ];
      //进行表单检查
      let checkRes = graceChecker.check(this.addressInfo, rule);
      if (checkRes) {
        this.submitAddressInfo();
      } else {
        uni.showToast({ title: graceChecker.error, icon: "none" });
      }
    },
    //新增或编辑地址
    submitAddressInfo () {
      if (this.id) {
        AddressUpdate({
          id: this.id,
          contact: this.addressInfo.contact,
          contactMobile: this.addressInfo.contactMobile,
          districtId: this.addressInfo.districtId,
          street: this.addressInfo.street
        }, (res) => {
          if(res.status == 0){
            uni.showToast({
              title:'编辑地址成功！',
              icon:'none',
              success: () => {
                console.log(this.sourceType, '898889')
                if (this.sourceType) {
                  if (this.sourceIsCar) {
                    setTimeout(function () {
                      uni.navigateTo({
                        url: '/pages/user/address?type=' + 1 + '&isCartBy=' + 1
                      })
                    }, 2000);
                  } else {
                    setTimeout(function () {
                      uni.navigateTo({
                        url: '/pages/user/address?type=' + 1
                      })
                    }, 2000);
                  }
                } else {
                  setTimeout(function () {
                    uni.navigateTo({
                      url:'/pages/user/address'
                    })
                  }, 2000);
                }
              }
            })
          }else{
            uni.showToast({
              title:res.msg,
              icon:'none'
            })
          }
        })
      } else {
        AddressSave ({
          contact: this.addressInfo.contact,
          contactMobile: this.addressInfo.contactMobile,
          districtId: this.addressInfo.districtId,
          street: this.addressInfo.street
        },(res) => {
          if (res.status == 0) {
            uni.showToast({
              title:'新增地址成功！',
              success: () => {
                if (this.sourceType) {
                  if (this.sourceIsCar) {
                    setTimeout(function () {
                      uni.navigateTo({
                        url: '/pages/user/address?type=' + 1 + '&isCartBy=' + 1
                      })
                    }, 2000);
                  } else {
                    setTimeout(function () {
                      uni.navigateTo({
                        url: '/pages/user/address?type=' + 1
                      })
                    }, 2000);
                  }
                } else {
                  setTimeout(function () {
                    uni.navigateTo({
                      url:'/pages/user/address'
                    })
                  }, 2000);
                }
              }
            });
          } else {
            uni.showToast({
              title: res.msg,
              icon:"none",
            })
          }
        })
      }
    },
  }
}
</script>

<style scoped lang="scss">
  .add-address-view {
    height: 100vh;
    .btn_div {
      width: 100%;
      height: 451rpx;
      background: #FFF;
    }
    /* 下拉框 */
    .gender_div{
      width: 100%;
      height: 300rpx;
      text-align: center;
      background:#FFF;
    }
    .gender{
      width: 60%;
      line-height: 70rpx;
      padding-top:40rpx;
      margin:0 auto;
    }
    .gender view{
      border-bottom:2rpx solid #03ccbb;
    
    }
    
    /* 三角形 */
      .arrow {
        border-right: 3rpx solid #8A8A8A;
        border-top: 3rpx solid #8A8A8A;
        height: 18rpx;
        width: 18rpx;
        transform: rotate(45deg);
        -webkit-transform: rotate(45deg);
        /*不加这两个属性三角会比上一个略丑, 大家可以试一下*/
        border-left: 2rpx solid transparent;
        border-bottom: 2rpx solid transparent;
      }
    /* 列表 */
    .unction_btn {
      display: flex;
      justify-content: center;
      // align-items: center;
      width: 718.8rpx;
      height: 97rpx;
      line-height: 97rpx;
      border-bottom: 2rpx solid #E1E1E1;
      opcity: 0.5;
      position: relative;
      margin-left:31rpx;
    }
    .unction_btn>text {
      
      // position: absolute;
      // left: 8rpx;
    }
    
    .unction_btn .arrow {
      position: absolute;
      right: 29rpx;
      top: 40rpx;
    }
    .uni-input {
      flex: 1;
      height: 97rpx;
      // margin-left: 20rpx;
      // position: absolute;
      // top: 36rpx;
      // left: 162rpx;
      font-size: 28rpx;
      font-family: PingFang SC;
      font-weight: 500;
    }
    .uni-input2 {
      flex: 1;
      // position: absolute;
      // top: 4rpx;
      // right: 65rpx;
      font-size: 28rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: #333333;
    }
    .uni-input1 {
      // position: absolute;
      // top: 330rpx;
      // left: 34rpx;
      padding: 34rpx 0 0 34rpx;
      font-size: 28rpx;
      color: #333333;
      font-family: PingFang SC;
      font-weight: 500;
      
    }
    
    .textarea-placeholder {
      font-size: 24rpx !important;
      color: #999999 !important;
    }
    
    .choice {
      position: absolute;
      top: 0rpx;
      right: 65rpx;
    }
    
    .btn_font {
      width: 140rpx;
      font-size: 28rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: rgba(51, 51, 51, 1);
    }
    /* 三角形 */
    .arrow {
      border-right: 3rpx solid #8A8A8A;
      border-top: 3rpx solid #8A8A8A;
      height: 18rpx;
      width: 18rpx;
      transform: rotate(45deg);
      -webkit-transform: rotate(45deg);
      /*不加这两个属性三角会比上一个略丑, 大家可以试一下*/
      border-left: 2rpx solid transparent;
      border-bottom: 2rpx solid transparent;
    }
    .input-placeholder {
      font-size: 24rpx;
      color: #999999;
    }
      
    .pick-value-select {
      color: #333333;
      font-size: 28rpx;
    }
      
    .pick-value {
      color: #999999;
      font-size: 24rpx;
    }
    /* 下面的button按钮 */
    .uni-common-mt button {
      width: 687rpx;
      height: 70rpx;
      background: #434343;
      font-size:30rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: rgba(246, 218, 153, 1);
      margin:21rpx auto;
    }
    .uni-common-mt{
      width: 100%;
      position:absolute;
      bottom:0;
      height: 112rpx;
      border-top:2rpx solid #E1E1E1;
    }
  }
  
</style>
